import type { AppProps } from 'next/app';
import React, { useContext, useEffect, useRef, useState } from 'react';
import SideBar from '@/components/layout/side-bar';
import { CssVarsProvider, ThemeProvider, useColorScheme } from '@mui/joy/styles';
import { joyTheme } from '@/defaultTheme';
import TopProgressBar from '@/components/layout/top-progress-bar';
import { useTranslation } from 'react-i18next';
import { ChatContext, ChatContextProvider } from '@/app/chat-context';
import classNames from 'classnames';
import '../styles/globals.css';
import '../nprogress.css';
import '../app/i18n';
import { STORAGE_LANG_KEY, STORAGE_THEME_KEY } from '@/utils';
import { ConfigProvider, theme, FloatButton, Image } from 'antd';
import { CommentOutlined } from '@ant-design/icons';
import zhCN from 'antd/locale/zh_CN';
import enUS from 'antd/locale/en_US';
import { Resizable } from 're-resizable';
import CryptoJS from 'crypto-js';
import { getNumberToken } from '@/client/api/request';
type ThemeMode = ReturnType<typeof useColorScheme>['mode'];
function getDefaultTheme(): ThemeMode {
  const theme = localStorage.getItem(STORAGE_THEME_KEY) as ThemeMode;
  if (theme) return theme;
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function CssWrapper({ children }: { children: React.ReactElement }) {
  const { i18n } = useTranslation();
  const { mode, setMode } = useColorScheme();
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const themeMode = getDefaultTheme();
    setMode(themeMode!);
  }, [setMode]);

  useEffect(() => {
    if (ref?.current && mode) {
      ref?.current?.classList?.add(mode);
      if (mode === 'light') {
        ref?.current?.classList?.remove('dark');
      } else {
        ref?.current?.classList?.remove('light');
      }
    }
  }, [ref, mode]);

  useEffect(() => {
    i18n.changeLanguage && i18n.changeLanguage(window.localStorage.getItem(STORAGE_LANG_KEY) || 'en');
  }, [i18n]);

  return (
    <div ref={ref}>
      <TopProgressBar />
      <ChatContextProvider>{children}</ChatContextProvider>
    </div>
  );
}

function LayoutWrapper({ children }: { children: React.ReactNode }) {
  const { isMenuExpand } = useContext(ChatContext);
  const { mode } = useColorScheme();
  const { i18n } = useTranslation();

  const [showFloatBtn, setFloatBtn] = useState(true);
  // INFO: showChat默认为true可以直接展示聊天对话框
  const [showChat, setShowChat] = useState(false);
  const iframeRef = useRef(null);
  const [numberPersonSrc, setNumberPersonSrc] = useState('');
  let dialogRef = useRef(null);
  let appKey = '7zwsd7rjjc3xyzf5';
  /* componentDidMount(){

  }; */

  const handleMessage = (res: any) => {
    // if(typeof res.data === 'boolean'){
    //   setShowChat(false);
    //   setFloatBtn(res.data);
    // }
    if(res.data.eventType=="close"){
      window.parent.postMessage({ text: '', eventType: 'close' },process.env.NEXT_PUBLIC_DAPING_BASE_URL)
      // setShowChat(false);
    }
    debugger
  };
  const closeChat = ()=>{
    const iframeDom = document.getElementById('numberPerson');
    // 给子页面发送消息
    console.log(process.env.NEXT_PUBLIC_HUMAN_BASE_URL)

    iframeDom&&iframeDom.contentWindow.postMessage({ text: "", eventType: 'close' }, process.env.NEXT_PUBLIC_HUMAN_BASE_URL);
    debugger
    // 给父页面发送消息
    window.parent.postMessage({ text: '', eventType: 'close' },process.env.NEXT_PUBLIC_DAPING_BASE_URL)
    setShowChat(!showChat);
    // 子页面拿到关闭的消息之后再设置
  }
  const openChat = () =>{
    const iframeDom = document.getElementById('numberPerson');
    // 给子页面发送消息
    iframeDom&&iframeDom.contentWindow.postMessage({ text: "", eventType: 'start' }, process.env.NEXT_PUBLIC_HUMAN_BASE_URL);
    setShowChat(true)
    // 给父页面发送消息
    window.parent.postMessage({ text: '', eventType: 'open' },process.env.NEXT_PUBLIC_DAPING_BASE_URL)
  }
  const loadIframe = () => {
    /*   setFloatBtn(true); */
    console.log(iframeRef.current);

    console.log('loaded');
  };
  useEffect(() => {
    // 接受子页面的消息
    const width = window.innerWidth;
    const height = window.innerHeight;
    const body = document.body;
    body.style.setProperty('--h', 100 / 1080 + '');
    body.style.setProperty('--w', 100 / 1920 + '');
    /*  window.addEventListener('resize',()=>{
      const width = window.innerWidth;
      const height = window.innerHeight;
      const body = document.body;
      body.style.setProperty('--h',100/height+'');
      body.style.setProperty('--w',100/width+'')
    }) */

    const element = iframeRef.current;
    let paramMap:any = {
      appId: "kcbtzaet",
      appKey: "7zwsd7rjjc3xyzf5"
    };
    getNumberToken(paramMap).then((res) => {
      console.log(res);
      const url = `https://ai.it.10086.cn:9060/digitalhuman/digitalhuman-cmit-h5/2D-h5/bigScreen?isSecret=0&appid=kcbtzaet&isWebrtc=1&eip=117.132.181.235&token=${res.data}`;
      setNumberPersonSrc(url);
      console.log(res.data);
    });

    element?.addEventListener('load', loadIframe);
    window.addEventListener('message', handleMessage);
    return () => {
      element.removeEventListener('load', loadIframe);
      window.removeEventListener('message', handleMessage);
    };
  }, []);
  /* const [chatWinSize, setChatWinSize] = useState({ width: 827, height: 520 }); */
  const [chatWinSize, setChatWinSize] = useState({ width: 926, height: 830 });
  /* const handle = ()=>{
    let dialog = document.querySelector("#dialog");
    dialog?.show();
  } */
  return (
    <ConfigProvider
      locale={i18n.language === 'en' ? enUS : zhCN}
      theme={{
        token: {
          borderRadius: 4,
        },
        algorithm: mode === 'dark' ? theme.darkAlgorithm : undefined,
      }}
    >
      <div className="flex w-screen h-screen overflow-hidden">
        {/* {
          <iframe
            id="mapIframe"
            ref={iframeRef}
            src="http://172.18.2.206:3000/dapin/#/home"
            style={{ width: '100vw', height: '100vh', position: 'relative' }}
          />
        }  */}
        {/* {{
          <iframe
            id="mapIframe"
            ref={iframeRef}
            src={process.env.NEXT_PUBLIC_DAPING_BASE_URL}
            style={{ width: '100vw', height: '100vh', position: 'relative' }}
          />
        } } */}
        {showFloatBtn && !showChat && (
          <div
            className="flex"
            style={{ width: '100%', height: '40px', }}
            onClick={openChat}
          >
            <img src="../recorderEnd.png" alt="" style={{ width: '40px', height: '40px' }} />

            <div className="robot">
              <span className="">我是chatBI机器人，请输入你的问题……</span>
            </div>
          </div>
        )}
        {
          <div>
            {/* <img src="../numberPerson.png" alt="" className="numberPerson" style={{ display: showChat ? '' : 'none' }} /> */}
            {/* <iframe id="numberPerson" ref={iframeRef} className="numberPerson" src={numberPersonSrc} style={{ display: showChat ? '' : 'none' }} /> */}
            {<iframe id="numberPerson" ref={iframeRef} className="numberPerson" src={process.env.NEXT_PUBLIC_HUMAN_BASE_URL} style={{ display: showChat ? '' : 'none' }}/>}
            {/* <NumberPerson></NumberPerson> */}
            <div className="modal" style={{ display: showChat ? '' : 'none' }}>
              {
                /* showChat&& */ <Resizable
                  enable={{
                    top: true,
                    right: false,
                    bottom: false,
                    left: false,
                    topRight: false,
                    bottomRight: false,
                    bottomLeft: false,
                    topLeft: false,
                  }}
                  /* size={{ width: chatWinSize.width, height: chatWinSize.height }}
              maxHeight="646px"
              minHeight="300px"
              maxWidth='926' */
                  onResizeStop={(e, direction, ref, d) => {
                    /* setChatWinSize({ width: chatWinSize.width, height: chatWinSize.height + d.height }); */
                  }}
                  className="flex flex-col overflow-hidden chat-resizable"
                >
                  <div
                    style={{
                      height: '100%',
                    }}
                  >
                    {children}
                  </div>
                </Resizable>
              }
              {
                /* showChat&& */ <img
                  src="../close.png"
                  alt=""
                  onClick={
                    closeChat
                  }
                  style={{
                    width: 'calc(26vw * var(--w))',
                    height: 'calc(26vh * var(--h))',
                    position: 'absolute',
                    zIndex: '210',
                    right: 'calc((100vw - 1447vw * var(--w)) / 2 - 40vw * var(--w))',
                    top: 'calc((100vh - 870vh * var(--h)) / 2)',
                    cursor: 'pointer',
                  }}
                />
              }
            </div>
          </div>
        }

        {/* showFloatBtn && (
          <FloatButton
            shape="circle"
            type="primary"
            style={{ left: '90%', bottom: '93%' }}
            className=''
            icon={<CommentOutlined />}
            onClick={() => setShowChat(!showChat)}
          />
        ) */}
      </div>
    </ConfigProvider>
  );
}

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <ThemeProvider theme={joyTheme}>
      <CssVarsProvider theme={joyTheme} defaultMode="light">
        <CssWrapper>
          <LayoutWrapper>
            <Component {...pageProps} />
          </LayoutWrapper>
        </CssWrapper>
      </CssVarsProvider>
    </ThemeProvider>
  );
}

export default MyApp;
